#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/ipc.h>
#include <cerrno>
#include <sys/types.h>
#include <sys/shm.h>
#include <cstdlib>
#include <cstring>
#include <sys/stat.h>
#include <cassert>

#define ssize 4096
#define PATHNAME "."
#define PROJID 0x6666
#define SERVER 1
#define CLIENT 0

class init
{
public:
    int creatshm(int key, int size, int flag)
    {
        int id = shmget(key, size, flag);
        if (id == -1)
        {
            std::cerr << "error: " << errno << ": " << strerror(errno) << std::endl;
            exit(2);
        }
        return id;
    }

    void delshm(int shmid)
    {
        shmctl(shmid, IPC_RMID, nullptr);
    }

    char* attach(int shmid)
    {
        char *ptr = (char *)shmat(shmid, nullptr, 0);
    }

    void delattch(char *start)
    {
        int n = shmdt(start);
        assert(n != -1);
    }

    init(int type)
    :_type(type)
    {
        umask(0);
        int _key = ftok(PATHNAME,PROJID);
        if(type)
        {
            _id = creatshm(_key,ssize,IPC_CREAT|IPC_EXCL|0666);
        }
        else
        {
            _id = creatshm(_key,ssize,IPC_EXCL|0666);
        }
        _start = attach(_id);
    }

    char* getstart()
    {
        return _start;
    }

    ~init()
    {
        delattch(_start);
        if(_type== SERVER) delshm(_id);
    }

private:
    char* _start;
    int _id;
    int _type;
};

#endif